package cn.zkteco.doordu.ui;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

import cn.zkteco.doordu.R;
import cn.zkteco.doordu.adapter.DeviceAdapter;
import cn.zkteco.doordu.model.Device;
import cn.zkteco.doordu.proxy.LeProxy;

/**
 * Created by Administrator on 2017/10/11.
 */

public class ScanA extends AppCompatActivity implements SwipeRefreshLayout.OnRefreshListener, AdapterView.OnItemClickListener {

    private static final String TAG = "ScanA";
    private static final int SCAN_PERIOD = 5000;
    private static final int REQUEST_ENABLE_BT = 2;

    private BluetoothAdapter mBluetoothAdapter;
    private Handler mHandler = new Handler();
    private boolean mScanning;


    ListView lvDevice;
    SwipeRefreshLayout refreshLayout;

    DeviceAdapter adapter;
    List<Device> list;
    List<String> macs;

    private BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback() {
        @Override
        public void onLeScan(final BluetoothDevice device, final int rssi, final byte[] scanRecord) {
            if (!macs.contains(device.getAddress())){
                System.out.println("------>new Device:"+device.getAddress());

                macs.add(device.getAddress());
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        list.add(new Device(device.getName(), device.getAddress(), rssi, scanRecord));
                        adapter.notifyDataSetChanged();
                    }
                });
            }
        }
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_scan);

        checkBle();
        initUI();

    }

    private void initUI() {
        refreshLayout = (SwipeRefreshLayout) findViewById(R.id.refreshLayout);
        lvDevice = (ListView) findViewById(R.id.lvDevice);

        list = new ArrayList<>();
        macs = new ArrayList<>();

        refreshLayout.setOnRefreshListener(this);

        adapter = new DeviceAdapter(this, list);

        lvDevice.setAdapter(adapter);
        lvDevice.setOnItemClickListener(this);
    }


    private void checkBle() {
        if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
            Toast.makeText(this, R.string.ble_not_supported, Toast.LENGTH_SHORT).show();
            finish();
        }

        final BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
        mBluetoothAdapter = bluetoothManager.getAdapter();

        if (mBluetoothAdapter == null) {
            Toast.makeText(this, R.string.error_bluetooth_not_supported, Toast.LENGTH_SHORT).show();
            finish();
            return;
        }

        if (!mBluetoothAdapter.isEnabled()) {
            Intent mIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(mIntent, 1);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (!mBluetoothAdapter.isEnabled()) {
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
        }
        scanLeDevice(true);
    }

    private void scanLeDevice(final boolean enable) {
        if (enable) {
            if (mBluetoothAdapter.isEnabled()) {
                if (mScanning)
                    return;
                mScanning = true;
                list.clear();
                macs.clear();
                mHandler.postDelayed(mScanRunnable, SCAN_PERIOD);
                mBluetoothAdapter.startLeScan(mLeScanCallback);
            } else {
                Toast.makeText(this, "蓝牙未打开", Toast.LENGTH_SHORT).show();
            }
        } else {
            mBluetoothAdapter.stopLeScan(mLeScanCallback);
            refreshLayout.setRefreshing(false);
            mHandler.removeCallbacks(mScanRunnable);
            mScanning = false;
        }
    }

    private final Runnable mScanRunnable = new Runnable() {
        @Override
        public void run() {
            scanLeDevice(false);
        }
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_ENABLE_BT && resultCode == RESULT_CANCELED) {
            finish();
            return;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onRefresh() {
        scanLeDevice(true);
    }

    @Override
    protected void onPause() {//stop scan
        super.onPause();
        scanLeDevice(false);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Intent intent = new Intent(this, ControlA.class);
        intent.putExtra(LeProxy.DEVICE_NAME, list.get(position).name);
        intent.putExtra(LeProxy.DEVICE_ADDRESS, list.get(position).address);
        startActivity(intent);
//        Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
//        startActivity(intent);
    }
}
